package com.example.druid.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    //没有实体类,数据库中的东西,怎么获取？ ---> map
    @GetMapping("/query")
    public List<Map<String,Object>> getUserList(){
        String sql = "Select * from user";
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
        return mapList;
    }

    @GetMapping("/add")
    public String addUser(){
        String sql = "insert into user values(7,'Marry', 14, '2002-02-20', '999@qq.com')";
        jdbcTemplate.update(sql);
        return "add-ok";
    }

    @GetMapping("/update/{id}")
    public String updateUser(@PathVariable("id") int id){
        String sql = "update user set name=?, age=?, birthday=?, email=? where id=" + id;

        //封装对象
        Object[] objects = new Object[4];
        objects[0] = "张三";
        objects[1] = 30;
        objects[2] = "2002/03/30";
        objects[3] = "666@qq.com";
        jdbcTemplate.update(sql, objects);

        return "update-ok";
    }

    @GetMapping("/delete/{id}")
    public String deleteUser(@PathVariable("id") int id){
        String sql = "delete from user where id = ?";
        jdbcTemplate.update(sql,id);
        return "delete-ok";
    }
}
